package com.eastfair.home.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
//import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.eastfair.boot.request.PageParams;
import com.eastfair.boot.service.SuperServiceImpl;
import com.eastfair.constant.BusinessConstant;
import com.eastfair.core.base.R;
import com.eastfair.core.context.ContextUtil;
import com.eastfair.home.dao.ReportDrawingCategoryAuditHistoryMapper;
import com.eastfair.home.dto.ReportDrawingAuditHistoryDTO;
import com.eastfair.home.dto.ReportDrawingCategoryAuditHistoryDTO;
import com.eastfair.home.entity.ReportDrawingAudit;
import com.eastfair.home.entity.ReportDrawingCategoryAudit;
import com.eastfair.home.entity.ReportDrawingCategoryAuditHistory;
import com.eastfair.home.enumeration.ReportDrawingCategoryAuditHistoryAuditStatusEnum;
import com.eastfair.home.service.ReportDrawingAuditHistoryService;
import com.eastfair.home.service.ReportDrawingCategoryAuditHistoryService;
import com.eastfair.home.vo.ReportDrawingCategoryAuditHistoryVO;
import com.eastfair.venueservice.consts.CommonConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 业务实现类
 * 报馆图纸分类审核记录历史
 * </p>
 *
 * @author dq
 * @date 2022-08-08
 */
@Slf4j
@Service
//@DS("#thread.tenant")
public class ReportDrawingCategoryAuditHistoryServiceImpl extends SuperServiceImpl<ReportDrawingCategoryAuditHistoryMapper, ReportDrawingCategoryAuditHistory> implements ReportDrawingCategoryAuditHistoryService {

    @Resource
    private ReportDrawingAuditHistoryService reportDrawingAuditHistoryService;

    @Resource(name = "threadPoolTaskExecutor")
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    /**
     * 处理逻辑删除相关处理
     *
     * @param modelList 实体
     * @return 是否成功
     */
    @Override
    protected R<Boolean> handlerRemoveByIdsOfLogic(Collection<ReportDrawingCategoryAuditHistory> modelList) {
        modelList.forEach(s -> s.setIsDeleted(BusinessConstant.YES));
        return R.successDef();
    }

    @Override
    protected R<Boolean> handlerSave(ReportDrawingCategoryAuditHistory model) {
        model.setProjectId(ContextUtil.getProjectId());
        model.setSubsystemId(ContextUtil.getSubSystemId());
        return R.successDef();
    }

    @Override
    public Page<ReportDrawingCategoryAuditHistoryVO> listHistoryVOs(PageParams<ReportDrawingCategoryAuditHistoryDTO> pageParams) {
        Page<ReportDrawingCategoryAuditHistory> page = listHistory(pageParams);
        List<ReportDrawingCategoryAuditHistory> records = page.getRecords();

        Page<ReportDrawingCategoryAuditHistoryVO> voPage = new Page<>();
        BeanUtil.copyProperties(page, voPage);
        if (records == null || records.isEmpty()) {
            return voPage;
        }
        List<ReportDrawingCategoryAuditHistoryVO> voList = records
                .stream()
                .map(history -> BeanUtil.toBean(history, ReportDrawingCategoryAuditHistoryVO.class))
                .collect(Collectors.toList());
        voPage.setRecords(voList);
        return voPage;
    }

    @Override
    public Page<ReportDrawingCategoryAuditHistory> listHistory(PageParams<ReportDrawingCategoryAuditHistoryDTO> pageParams) {
        log.info("listReportDrawingCategoryAuditHistory - 查询报馆图纸分类审核历史列表, pageParams={}", pageParams);
        Page<ReportDrawingCategoryAuditHistory> page = pageParams.buildPage();
        ReportDrawingCategoryAuditHistoryDTO query = pageParams.getModel();
        QueryWrapper<ReportDrawingCategoryAuditHistory> queryWrapper = new QueryWrapper<>();
        queryWrapper
                .lambda()
                .eq(ReportDrawingCategoryAuditHistory::getIsDeleted, BusinessConstant.DELETE_NO)
                .eq(query.getReportSpaceId() != null, ReportDrawingCategoryAuditHistory::getReportSpaceId, query.getReportSpaceId())
                .eq(query.getDrawingCategoryId() != null, ReportDrawingCategoryAuditHistory::getDrawingCategoryId, query.getDrawingCategoryId())
                .eq(query.getReportSpaceAuditId() != null, ReportDrawingCategoryAuditHistory::getReportSpaceAuditId, query.getReportSpaceAuditId())
                .orderByDesc(ReportDrawingCategoryAuditHistory::getCreateTime)
        ;
        return page(page, queryWrapper);
    }

    @Override
    public List<ReportDrawingCategoryAuditHistory> listHistory(ReportDrawingCategoryAuditHistoryDTO historyDTO) {
        QueryWrapper<ReportDrawingCategoryAuditHistory> queryWrapper = createQueryWrapper(historyDTO);
        return list(queryWrapper);
    }

    @Override
    public ReportDrawingCategoryAuditHistory getLastHomeApprovedHistory(Long reportSpaceId, Long drawingCategoryId) {
        ReportDrawingCategoryAuditHistoryDTO query = new ReportDrawingCategoryAuditHistoryDTO();
        query.setReportSpaceId(reportSpaceId);
        query.setDrawingCategoryId(drawingCategoryId);
        query.setAuditStatus(ReportDrawingCategoryAuditHistoryAuditStatusEnum.APPROVED);
        List<ReportDrawingCategoryAuditHistory> list = listHistory(query);
        if (list == null || list.isEmpty()) {
            return null;
        }
        return list.get(0);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveHistory(ReportDrawingCategoryAuditHistoryDTO historyDTO) {
        ReportDrawingCategoryAuditHistory history = BeanUtil.toBean(historyDTO, ReportDrawingCategoryAuditHistory.class);
        save(history);
        List<ReportDrawingAuditHistoryDTO> drawingHistoryList = historyDTO.getReportDrawingAuditHistoryList();
        return reportDrawingAuditHistoryService.saveBatch(drawingHistoryList, history.getId());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveBatch(List<ReportDrawingCategoryAuditHistoryDTO> list) {
        if (list == null || list.isEmpty()) {
            return false;
        }
        list.forEach(this::saveHistory);
        return true;
    }

    @Override
    public void asyncSaveBatch(List<ReportDrawingCategoryAuditHistoryDTO> list) {
        threadPoolTaskExecutor.execute(() -> saveBatch(list));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveBatchByReportDrawingCategoryAudit(List<ReportDrawingCategoryAudit> categoryList, List<ReportDrawingAudit> drawingList) {
        Map<Long, List<ReportDrawingAudit>> reportDrawingAuditMap = drawingList
                .stream()
                .collect(Collectors.groupingBy(ReportDrawingAudit::getReportDrawingCategoryAuditId));
        // 图纸分类审核列表转为图纸分类审核历史列表
        CopyOptions copyOptions = CopyOptions
                .create()
                .setIgnoreProperties(CommonConstants.COMMON_IGNORE_PROPERTIES);
        List<ReportDrawingCategoryAuditHistoryDTO> historyDTOList = categoryList
                .stream()
                .map(audit -> {
                    ReportDrawingCategoryAuditHistoryDTO historyDTO = BeanUtil.toBean(audit, ReportDrawingCategoryAuditHistoryDTO.class, copyOptions);
                    historyDTO.setReportDrawingCategoryAuditId(audit.getId());

                    List<ReportDrawingAudit> reportDrawingAuditList = reportDrawingAuditMap.get(audit.getId());
                    List<ReportDrawingAuditHistoryDTO> reportDrawingAuditHistoryList = reportDrawingAuditHistoryService.toReportDrawingAuditHistoryDTOList(reportDrawingAuditList);
                    historyDTO.setReportDrawingAuditHistoryList(reportDrawingAuditHistoryList);
                    return historyDTO;
                })
                .collect(Collectors.toList());
        // 批量保存图纸分类审核历史
        asyncSaveBatch(historyDTOList);
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateHistoryByVenue(ReportDrawingCategoryAuditHistoryDTO historyDTO) {
        log.info("updateHistoryByVenue - 场馆审核更新审核历史, historyDTO={}", historyDTO);
        ReportDrawingCategoryAuditHistory history = getLastHomeApprovedHistory(historyDTO.getReportSpaceId(), historyDTO.getDrawingCategoryId());
        if (history == null) {
            return false;
        }
        history.setVenueAuditStatus(historyDTO.getVenueAuditStatus());
        history.setVenueAuditOpinion(historyDTO.getVenueAuditOpinion());
        history.setVenueAuditTime(historyDTO.getVenueAuditTime());
        history.setVenueAuditUserId(historyDTO.getVenueAuditUserId());
        history.setVenueAuditUserName(historyDTO.getVenueAuditUserName());
        history.setDrawingAuditStatus(historyDTO.getDrawingAuditStatus());
        return updateById(history);
    }

    private QueryWrapper<ReportDrawingCategoryAuditHistory> createQueryWrapper(ReportDrawingCategoryAuditHistoryDTO query) {
        QueryWrapper<ReportDrawingCategoryAuditHistory> queryWrapper = new QueryWrapper<>();
        queryWrapper
                .lambda()
                .eq(ReportDrawingCategoryAuditHistory::getIsDeleted, BusinessConstant.DELETE_NO)
                .eq(query.getReportSpaceId() != null, ReportDrawingCategoryAuditHistory::getReportSpaceId, query.getReportSpaceId())
                .eq(query.getDrawingCategoryId() != null, ReportDrawingCategoryAuditHistory::getDrawingCategoryId, query.getDrawingCategoryId())
                .eq(query.getReportSpaceAuditId() != null, ReportDrawingCategoryAuditHistory::getReportSpaceAuditId, query.getReportSpaceAuditId())
                .eq(query.getAuditStatus() != null, ReportDrawingCategoryAuditHistory::getAuditStatus, query.getAuditStatus())
                .orderByDesc(ReportDrawingCategoryAuditHistory::getCreateTime)
        ;
        return queryWrapper;
    }

}
